package Bench::Test::View::Text;

use 5.008004;
use strict;
use warnings;

use Template;

sub process {
   my $data = shift;
   my $output;

   my $config = {
      INTERPOLATE => 1,  # expand "$var" in plain text
      POST_CHOMP  => 0,  # cleanup whitespace
      PRE_CHOMP   => 0,
      EVAL_PERL   => 1,  # evaluate Perl code blocks
   };

   # create Template object
   my $template = Template->new($config);

   # define template variables for replacement
   my $vars = {
      data => $data,
   };

   # process input template, substituting variables
   $template->process(\*DATA, $vars, \$output)
     || die $template->error();

   return $output;
}


1;

# Template for Plain Text output
__DATA__
[%- PERL -%]
   # =====================================================
   # PERL BLOCK:
   # Este bloque perl realiza un preprocesamiento de la 
   # entrada. Calcula la longitud maxima de los campos
   # y rellena con ceros para conseguir que los datos 
   # queden perfectamente alineados como una tabla
   # =====================================================

   sub fill_with_spaces {
      my ($length, $output) = @_;
      return $output.(" "x($length  - length($output)));
   }

   # ==================================================
   # MAIN
   # ==================================================
   my $data = $stash->get('data');
   my $nrows = @{$data};
   my $ncols = @{$data->[0]};
   my @max_lengths = ();

   for (my $c = 0; $c < $ncols; $c++) {
      my $max_length = length $data->[0][$c];
      for (my $r = 1; $r < $nrows; $r++) {
         if (length $data->[$r][$c] > $max_length) {
            $max_length = length $data->[$r][$c];
         }
      }
      push @max_lengths, $max_length;
   }

   for (my $c = 0; $c < $ncols; $c++) {
      for (my $r = 0; $r < $nrows; $r++) {
         $data->[$r][$c] = fill_with_spaces($max_lengths[$c], $data->[$r][$c]);
      }
   }
[%- END -%]

[%- FOREACH row IN data -%]
  [%- FOREACH item IN row -%]$item  [%- END %]
[% END -%]
